package com.hyt.it.ogt.api.ykcj;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyt.it.ogt.controller.base.BaseController;
import com.hyt.it.ogt.ykcj.common.core.domain.AjaxResult;
import com.hyt.it.ogt.ykcj.common.enums.CommonEnums;
import com.hyt.it.ogt.ykcj.common.enums.PublishTypeEnums;
import com.hyt.it.ogt.ykcj.common.enums.ShowTypeEnums;
import com.hyt.it.ogt.ykcj.domain.exchange.ApiExamPublishInfo;
import com.hyt.it.ogt.ykcj.domain.grade.EnterpriseExamineeInfo;
import com.hyt.it.ogt.ykcj.domain.grade.EnterpriseExamineeSubjectGrade;
import com.hyt.it.ogt.ykcj.domain.grade.ExamPublishInfo;
import com.hyt.it.ogt.ykcj.domain.vo.ExamInfoVo;
import com.hyt.it.ogt.ykcj.domain.vo.ExamSubjectVo;
import com.hyt.it.ogt.ykcj.domain.vo.ExamineeSubjectScoreVo;
import com.hyt.it.ogt.ykcj.domain.vo.export.ApiExamPublishInfoVo;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamSubjectInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.EnterpriseExamineeInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.EnterpriseExamineeSubjectGradeMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.ExamPublishInfoMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;

/**
 * description 对外提供发布考生成绩信息查询接口Controller
 *
 * @author liy
 * @createTime 2022/05/16
 */
@Api(tags = "API.14.对外提供查询考生考试发布信息", value = "对外提供查询考生考试发布信息")
@ApiSort(value = 1004)
@Slf4j
@RestController
@RequestMapping("/exam/publish/info")
public class ExamPublishInfoApi extends BaseController {



	@Autowired
	private EnterpriseExamineeInfoMapper enterpriseExamineeInfoMapper;

	@Autowired
	private ExamInfoMapper examInfoMapper;


	@Autowired
	private ExamSubjectInfoMapper eamSubjectInfoMapper;

	@Autowired
	private EnterpriseExamineeSubjectGradeMapper enterpriseExamineeSubjectGradeMapper;

	@Autowired
	private ExamPublishInfoMapper examPublishInfoMapper;

	/**
	 * 接收考试考试信息
	 * 
	 * @throws Exception
	 */
	@ApiOperation("获取考生发布考试信息")
	@ApiResponses(value = { @ApiResponse(code = 13000, message = "调用失败！"), })
	@PostMapping("/getApiExamPublishInfoVos")
	public AjaxResult getApiExamPublishInfoVos(@RequestBody List<ApiExamPublishInfo> apiExamPublishInfos) {
        if(CollectionUtils.isEmpty(apiExamPublishInfos)){
            return AjaxResult.error("参数为空！");
        }
        Set<String> paramExamIds = apiExamPublishInfos.stream().map(ApiExamPublishInfo::getExamId).collect(Collectors.toSet());
        Set<String> admissionNos = apiExamPublishInfos.stream().map(ApiExamPublishInfo::getAdmissionNo).collect(Collectors.toSet());
 		if(CollectionUtils.isEmpty(paramExamIds) || CollectionUtils.isEmpty(admissionNos)){
			return AjaxResult.error("考试ID或准考证号参数为空！");
		}
		Map<String,Object> parms = new HashMap<>();
		parms.put("examCodes",paramExamIds.toArray(new String [paramExamIds.size()]));
		List<ExamInfoVo> examInfos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
		if(CollectionUtils.isEmpty(examInfos)){
			return AjaxResult.success(Collections.EMPTY_LIST);
		}
		List<String> examIds = examInfos.stream().map(ExamInfoVo::getId).collect(Collectors.toList());

		List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoMapper.
				selectEnterpriseExamineeInfoByExamIdsAndAdmissionNos(examIds.toArray(new String [examIds.size()]),admissionNos.toArray(new String [admissionNos.size()]));
		if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
			return AjaxResult.success(Collections.EMPTY_LIST);
		}

 		Map<String,ExamInfoVo> examInfoMap = examInfos.stream().collect(Collectors.toMap(ExamInfoVo::getId, ExamInfoVo -> ExamInfoVo, (k1, k2) -> k2));
        //考试的所有科目
		List<ExamSubjectVo> examSubjectVos = eamSubjectInfoMapper.selectExamSubjectInfoByExamIds(examIds.toArray(new String [examIds.size()]));
		Map<String,String> examSubjectNameMap = examSubjectVos.stream().collect(Collectors.toMap(ExamSubjectVo::getSubjectId, ExamSubjectVo::getSubjectName, (k1, k2) -> k2));

		//发布的考试
		LambdaQueryWrapper<ExamPublishInfo> wrapper = Wrappers.lambdaQuery();
		wrapper.in(ExamPublishInfo::getExamId, examIds);
		List<ExamPublishInfo> allExamPublishInfos =  examPublishInfoMapper.selectList(wrapper);
		Map<String,List<ExamPublishInfo>> allExamPublishInfoMap = allExamPublishInfos.stream().collect(Collectors.groupingBy(d -> d.getExamId()));

		List<ApiExamPublishInfoVo>  vos = new ArrayList<>();
		for (EnterpriseExamineeInfo info : enterpriseExamineeInfos) {
			ApiExamPublishInfoVo vo = new ApiExamPublishInfoVo();
			vo.setAdmissionNo(info.getAdmissionNo());
			vo.setId(info.getExamId());
			vo.setReviewStatus(info.getReviewStatus());
			vo.setExamineeId(info.getId());
			if(MapUtils.isNotEmpty(examInfoMap) && null != examInfoMap.get(info.getExamId())){
				vo.setExamName(examInfoMap.get(info.getExamId()).getExamNameConfigName());
				vo.setExamStartDay(examInfoMap.get(info.getExamId()).getExamStartDay());
				vo.setExamEndDay(examInfoMap.get(info.getExamId()).getExamEndDay());
			}
			ExamineeSubjectScoreVo  examineeSubjectScoreVo = getExamineeSubjectScoreVo(info.getExamId(),info.getId(),examSubjectNameMap);

            if(null != examineeSubjectScoreVo &&  StringUtils.isNotEmpty(examineeSubjectScoreVo.getSubjectName())){
 				vo.setSubjectName(examineeSubjectScoreVo.getSubjectName());
			}


            vo.setResultScore(null);
            vo.setExamResult("--");
            if(MapUtils.isEmpty(allExamPublishInfoMap)){
                vo.setPublishStatus(Integer.valueOf(CommonEnums.CHECK_STATUS_0.getCode()));
                vo.setShowPaperStatus(Integer.valueOf(CommonEnums.CHECK_STATUS_0.getCode()));
				vo.setReviewStatus(null);
				vos.add(vo);
            	continue;
			}
            List<ExamPublishInfo> examPublishInfos = allExamPublishInfoMap.get(info.getExamId());
			if(CollectionUtils.isEmpty(examPublishInfos)){
                vo.setPublishStatus(Integer.valueOf(CommonEnums.CHECK_STATUS_0.getCode()));
                vo.setShowPaperStatus(Integer.valueOf(CommonEnums.CHECK_STATUS_0.getCode()));
				vo.setReviewStatus(null);
				vos.add(vo);
				continue;
			}
            Map<Integer,ExamPublishInfo> examPublishInfoMap = examPublishInfos.stream().collect(Collectors.toMap(ExamPublishInfo::getPublishType, examSubjectInfo -> examSubjectInfo,(key1,key2)->key2));
            if(null != examPublishInfoMap.get(PublishTypeEnums.PUBLISH_TYPE_0.getCode())) {
                vo.setPublishStatus(Integer.valueOf(CommonEnums.CHECK_STATUS_1.getCode()));
                ExamPublishInfo examPublishInfo = examPublishInfoMap.get(PublishTypeEnums.PUBLISH_TYPE_0.getCode());
                if (StringUtils.isNotEmpty(examPublishInfo.getShowType())) {
                    List<String> showTypes = Arrays.asList(examPublishInfo.getShowType().split(","));


                    //显示考试总成绩
					if( showTypes.contains(ShowTypeEnums.SHOW_TYPE_0.getCode())){
						vo.setResultScore(examineeSubjectScoreVo.getResultScore());
					}

                    //显示考试结果
                    if( showTypes.contains(ShowTypeEnums.SHOW_TYPE_1.getCode())){
                        if(StringUtils.isNotEmpty(info.getRegionName())){
                            vo.setExamResult(info.getRegionName());
                        }else if(StringUtils.isNotEmpty(info.getQualifiedStatus())){
                            if( CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(info.getQualifiedStatus())){
                                vo.setExamResult( CommonEnums.QUALIFIED_STATUS_Y.getDesc() );
                            }else if( CommonEnums.QUALIFIED_STATUS_N.getCode().equals(info.getQualifiedStatus())){
                                vo.setExamResult( CommonEnums.QUALIFIED_STATUS_N.getDesc() );
                            }

                        }else{
                            vo.setExamResult("--");
                        }
                    }
                }
            }
            if(null != examPublishInfoMap.get(PublishTypeEnums.PUBLISH_TYPE_2.getCode())){
				ExamPublishInfo examPublishInfo = examPublishInfoMap.get(PublishTypeEnums.PUBLISH_TYPE_2.getCode());
				//显示复核,不在有效期内的都不显示
				if(null != examPublishInfo.getStartDay() && examPublishInfo.getStartDay().getTime() > System.currentTimeMillis() ){
					vo.setReviewStatus(null);
				}else if(null != examPublishInfo.getEndDay() && examPublishInfo.getEndDay().getTime() < System.currentTimeMillis()){
					vo.setReviewStatus(null);
				}
			}else {
				vo.setReviewStatus(null);
			}
			if(null != examPublishInfoMap.get(PublishTypeEnums.PUBLISH_TYPE_1.getCode())){
				ExamPublishInfo examPublishInfo = examPublishInfoMap.get(PublishTypeEnums.PUBLISH_TYPE_1.getCode());
				if (StringUtils.isNotEmpty(examPublishInfo.getShowType())) {
					List<String> showTypes = Arrays.asList(examPublishInfo.getShowType().split(","));
					//显示试卷
					if( showTypes.contains(ShowTypeEnums.SHOW_TYPE_3.getCode()) || showTypes.contains(ShowTypeEnums.SHOW_TYPE_4.getCode())){
						vo.setShowPaperStatus(Integer.valueOf(CommonEnums.CHECK_STATUS_1.getCode()));
					}
					//不在有效期内的试卷不显示
					if(Integer.valueOf(CommonEnums.SEE_TYPE_1.getCode()).equals(examPublishInfo.getSeeType())){
						if(null != examPublishInfo.getStartDay() && examPublishInfo.getStartDay().getTime() > System.currentTimeMillis()){
							vo.setShowPaperStatus(Integer.valueOf(CommonEnums.CHECK_STATUS_0.getCode()));
						}else if(null != examPublishInfo.getEndDay() && examPublishInfo.getEndDay().getTime() < System.currentTimeMillis()){
							vo.setShowPaperStatus(Integer.valueOf(CommonEnums.CHECK_STATUS_0.getCode()));
						}
					}
				}
			}else {
				vo.setShowPaperStatus(Integer.valueOf(CommonEnums.CHECK_STATUS_0.getCode()));
			}
			vos.add(vo);
		}


		return AjaxResult.success(vos);
	}



	/**
	 *获取考生考试所考的科目信息
	 * @param examId
	 * @return
	 */
	private ExamineeSubjectScoreVo  getExamineeSubjectScoreVo(String examId,String examineeId,Map<String,String> examSubjectNameMap){

		//考试的所有科目
		List<ExamSubjectVo> examSubjectVos = eamSubjectInfoMapper.selectExamSubjectInfoByExamId(examId);
		if(CollectionUtils.isEmpty(examSubjectVos)){
			return null;
		}
		//考生考的科目
        BigDecimal resultScore = null;
        List<String> subjectName = new ArrayList<>();
		List<EnterpriseExamineeSubjectGrade> enterpriseExamineeSubjectGrades = enterpriseExamineeSubjectGradeMapper.selectArchiveEnterpriseExamineeSubjectGradeList(new String[]{examineeId}, examId,null);
		Map<String,  EnterpriseExamineeSubjectGrade> subjectScoreMap = enterpriseExamineeSubjectGrades.stream().collect(Collectors.toMap(EnterpriseExamineeSubjectGrade::getSubjectId, enterpriseExamineeSubjectGrade ->enterpriseExamineeSubjectGrade, (k1, k2) -> k2));
        ExamineeSubjectScoreVo examineeSubjectScoreVo = new ExamineeSubjectScoreVo();
		for (ExamSubjectVo examSubjectVo : examSubjectVos){
			if (MapUtils.isEmpty(subjectScoreMap) || null == subjectScoreMap.get(examSubjectVo.getSubjectId())) {
				continue;
			}
			if(MapUtils.isNotEmpty(examSubjectNameMap) && StringUtils.isNotEmpty(examSubjectNameMap.get(examSubjectVo.getSubjectId()))){
				subjectName.add(examSubjectNameMap.get(examSubjectVo.getSubjectId()));
			}
            if(null != subjectScoreMap.get( examSubjectVo.getSubjectId()).getScore()){
                if(null == resultScore){
                    resultScore = BigDecimal.ZERO;
                }
				resultScore = resultScore.add(subjectScoreMap.get(examSubjectVo.getSubjectId()).getScore());
            }
		}
        examineeSubjectScoreVo.setResultScore(resultScore);
        examineeSubjectScoreVo.setSubjectName(StringUtils.join(subjectName,"/"));
		return examineeSubjectScoreVo;
	}




}
